using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Xml;

namespace OCPL
{
    public class SPFieldSkypeStatus : SPField
    {
        bool _updating = false;

        public SPFieldSkypeStatus(SPFieldCollection fields, string fieldName)
            : base(fields, fieldName)
        {
        }

        public SPFieldSkypeStatus(SPFieldCollection fields, string typeName, string displayName)
            : base(fields, typeName, displayName)
        {
        }

        public override BaseFieldControl FieldRenderingControl
        {
            get
            {
                string skypeIconStyle = (string)base.GetCustomProperty("SkypeIconStyle");
                string behaviour = (string)base.GetCustomProperty("Behaviour");
                BaseFieldControl baseFieldControl = new SkypeStatusControl(skypeIconStyle, behaviour);
                baseFieldControl.FieldName = this.InternalName;
                return baseFieldControl;
            }
        }

        public override void OnUpdated()
        {
            if (_updating)
                return;
            _updating = true;

            base.OnUpdated();

            ConfigureSchemaXml();

            _updating = false;
        }

        public override void OnAdded(SPAddFieldOptions op)
        {
            base.OnAdded(op);
            ConfigureSchemaXml();
        }

        private void ConfigureSchemaXml()
        {
            string skypeIconStyle = (string)base.GetCustomProperty("SkypeIconStyle");
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(base.SchemaXml);
            if (doc.FirstChild.Attributes["SkypeIconStyle"] == null)
            {
                XmlAttribute attrib = doc.CreateAttribute("SkypeIconStyle");
                attrib.Value = skypeIconStyle;
                doc.FirstChild.Attributes.Append(attrib);
            }
            else
            {
                doc.FirstChild.Attributes["SkypeIconStyle"].Value = skypeIconStyle;
            }
            base.SchemaXml = doc.OuterXml;
        }
    }
}